// 2.1 抽取初始化状态initState
// 2.2 提取到reducer.js中单独维护
const initState = {
  list: [
    {
      id: 1,
      name: 'JS',
      isDone: false,
    },
    {
      id: 2,
      name: 'React',
      isDone: true,
    },
    {
      id: 3,
      name: 'Redux',
      isDone: false,
    },
  ],
  type: 'completed',
};
// 1.1 初始化state:{list, type}
export default function reducer(state = initState, action) {
  console.warn('Redux-Logger: 收到action->', action);
  const { type, payload } = action;
  switch (type) {
    //  4.2 reducer.js中定义toggle
    case 'toggle':
      // 4.3 根据id计算新的list状态，并返回state
      return {
        // 复制state
        ...state,
        // list新值覆盖list属性
        list: state.list.map((item) => ({
          ...item,
          // isDone新值覆盖isDone属性
          isDone: item.isDone === payload ? !item.isDone : item.isDone,
        })),
      };

    // 5.2 reducer.js中定义del
    case 'del':
      // 5.3 根据id计算删除后的list状态，并返回state
      return {
        ...state,
        // 筛选id与删除id不同的元素组成新的list
        list: state.list.filter((item) => item.id !== payload),
      };
    // 6.4 定义toggleType的计算，并返回新的state
    case 'toggleType':
      return {
        ...state,
        type: payload,
      };

    default:
      return state;
  }
}
